<template>
  <div class="log-details w-full h-full over-flow-hidden display-flex-column">
    <!--    上方的界面-->
    <div class="stage-box w-full" style="position: relative">
      <!--    右上角的业务类型  -->
      <div style="position: absolute; right: 20px;top: 5%">
        <span>业务类型：{{businessName}}</span>
      </div>
      <!--     流程图-->
      <project-interface-act
        ref="projectInterfaceAct"
        v-if="modelId"
        :model-id="modelId"
        :stageList="stageList"
        @handlerSelectAct="handlerSelectedDetails"
      />
      <!--    右下角的分页框  -->
      <div style="position: absolute; right: 10px;top: 85%; transform: scale(0.8,0.8);">
        <a-pagination
          :current="currentPage"
          :pageSize="1"
          :total="pageTotal"
          @change="onPageChange"
        />
      </div>
    </div>
    <!--    下方的具体详情tab页-->
    <div class="w-full flex-1 m-t-sm display-flex over-flow-hidden" style="height: 60%">
      <div class="h-full flex-1 content-tab over-flow-hidden border" style="overflow:hidden;position: relative;">
        <div class="h-full over-flow-hidden" :class="{'flex-column':currentType === 'table','flex-row':currentType === 'material'}" v-if="selectedDetails.length > 0" style="overflow:hidden;display: flex;">
          <a-tabs
            :size="'small'"
            :active-key="activeKey"
            @change="handlerChangeTab"
            class="w-full h-full over-flow-hidden">
            <a-tab-pane v-for="item in selectedDetails" :key="item.id" :tab="item.stageName">
              <!--     表格展示       -->
              <a-descriptions v-if="currentType === 'table'" :column="2" bordered>
                <a-descriptions-item :label="col.label" v-for="col in columns" :key="col.key">
                  <div v-if="col.type === 'date'">
                    {{ item[col.key] ? moment(item[col.key]).format('YYYY-MM-DD HH:mm:ss') : '' }}
                  </div>
                  <div v-else-if="col.type === 'time'">
                    {{ getTime(item.startTime, item.endTime) + 'ms' }}
                  </div>
                  <div v-else-if="col.type === 'async'">
                    {{ item.isAsync ? '是' : '否' }}
                  </div>
                  <div v-else-if="col.type === 'packageButton'">
                    <a-button v-show="item[col.key]" size="small" @click="handlerShowJson(item[col.key],item)">查看详情
                    </a-button>
                  </div>
                  <div v-else>
                    {{ item[col.key] || col.default }}
                  </div>
                </a-descriptions-item>
              </a-descriptions>
              <!--     材料展示       -->
              <material-upload class="projectMaterials" v-if="currentType === 'material'" :projectId="projectId"/>
            </a-tab-pane>
          </a-tabs>
          <div class="content-button-list flex-1 display-flex">
            <a-button class="content-button" type="primary" @click="interfaceRepush">接口补调</a-button>
            <a-button
              class="content-button"
              type="primary"
              v-if="showRepushButton"
              :disabled="disableRepushButton"
              @click="materialRepush"
            >
              重推批复
            </a-button>
          </div>
        </div>
        <div class="display-flex w-full h-full" v-else>
          <h1 style="opacity: 0.5">请选择阶段</h1>
        </div>
      </div>
      <!--  表格与展示数据的分割线    -->
      <div class="h-full" v-if="currentType === 'table'" style="width: 10px"></div>
      <!--  json解析数据展示    -->
      <div class="h-full flex-1 over-flow-hidden border" v-if="currentType === 'table'" style="overflow:hidden">
        <vue-json-editor
          class="w-full h-full"
          v-if="jsonData"
          v-model="jsonData"
          :showBtns="false"
          :mode="'code'"
          lang="zh"/>
        <div class="display-flex w-full h-full" v-else>
          <h1 style="opacity: 0.5">请选择展示数据</h1>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ProjectInterfaceAct from './ProjectInterfaceAct'
import vueJsonEditor from 'vue-json-editor'
import moment from 'moment'
import interfaceMonitorService from "@/api/interfaceMonitorService";
import projectReplaceMaterials from "../dialog/ProjectReplaceMaterials"
import materialUpload from "./MaterialUpload"
import sqlService from '@/api/sqlService'
import dicService from "@/api/dicService";

const columns = [
  {
    label: 'id标识',
    key: 'id',
    default: '/'
  },
  {
    label: 'label',
    key: 'activityName',
    default: '/'
  },
  {
    label: '源系统项目Id',
    key: 'projectId',
    default: '/'
  },
  {
    label: '阶段名称',
    key: 'stageName',
    default: '/'
  },
  {
    label: '请求标识',
    key: 'requestId',
    default: '/'
  },
  {
    label: '开始时间',
    key: 'startTime',
    default: '/',
    type: 'date'
  },
  {
    label: '结束时间',
    key: 'endTime',
    default: '/',
    type: 'date'
  },
  {
    label: '时间消耗',
    key: 'startTime',
    default: '/',
    type: 'time'
  },
  {
    label: '状态码',
    key: 'statusCode',
    default: '/'
  },
  {
    label: '是否为异步接口',
    key: 'isAsync',
    default: '/',
    type: 'async'
  },
  {
    label: '阶段组编号',
    key: 'groupCode',
    default: '/'
  },
  {
    label: '数据包信息',
    key: 'dataPackage',
    default: '/',
    type: 'packageButton'
  },
  {
    label: '请求体信息',
    key: 'requestData',
    default: '/',
    type: 'packageButton'
  },
  {
    label: '响应体信息',
    key: 'responseData',
    default: '/',
    type: 'packageButton'
  },
  {
    label: '数据包详情',
    key: 'dataPackageSize',
    default: '/',
    type: 'downloadDataPackage'
  }
]
export default {
  name: 'ProjectFullInterface',
  components: {ProjectInterfaceAct, vueJsonEditor, projectReplaceMaterials,materialUpload},
  props: {
    dataSource:{
      type: Object,
      default:() => {}
    }
  },
  watch: {
    dataSource:function (newValue,oldValue) {
      this.dataSource = newValue
      this.stageList = newValue.fullStage
      this.jsonData = null
    },
    showRepushButton:function (newValue, oldValue) {
      this.showRepushButton = newValue
      //重推批复按钮显示时判断其是否能够点击
      if (newValue) {
        this.disableMaterialRepushButton()
      }
    }
  },
  data() {
    return {
      moment,
      columns,
      projectId: 0,
      modelId:null,
      businessName: '',
      currentPage:1,
      pageTotal:0,
      stageList: [],
      activeKey: '',
      selectedDetails: [],
      selectedStage: '',
      currentType: 'table',
      disableRepushButton:true,
      showRepushButton:false,
      jsonData: null,
      tableDataInfo: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    //初始化数据
    async init() {
      this.projectId = this.dataSource.projectId
      this.businessName = this.dataSource.businessName
      this.stageList = this.dataSource.fullStage
      this.pageTotal = this.dataSource.pageTotal
      const d = await dicService.listDicItemByDicName('接口监控流程图', null)
      if (d && d.length > 0) {
        this.modelId = d[0].value
      }
    },
    //展示选择的接口调用详情
    async handlerSelectedDetails(selectedDetails,selectedStage) {
      this.selectedDetails = selectedDetails
      this.selectedStage = selectedStage
      if (selectedDetails[0].type) {
        this.currentType = selectedDetails[0].type;
      }
      this.activeKey = selectedDetails[0].id
      this.jsonData = null
      this.showRepushButton = this.showMaterialRepushButton()
    },
    //切换展示的详情tab页
    handlerChangeTab(activeKey) {
      this.activeKey = activeKey
      const selectActive = this.selectedDetails.find(item => item.id === this.activeKey)
      if (selectActive.type) {
        this.currentType = selectActive.type;
      }
      this.jsonData = null
      this.showRepushButton = this.showMaterialRepushButton()
    },
    //计算接口调用消耗事件
    getTime(startTime, endTime) {
      const startDate = new Date(startTime)
      const endDate = new Date(endTime || startTime)
      return (endDate - startDate) / 1000
    },
    //解析并展示Json数据
    async handlerShowJson(jsonStr) {
      const msg = await this.handlerJsonMsg(jsonStr)
      this.jsonData = JSON.parse(jsonStr)
      this.jsonData.msg = msg
    },
    //处理json数据
    async handlerJsonMsg (jsonStr) {
      const jsonInfo = JSON.parse(jsonStr)
      const jsonMsg = jsonInfo && jsonInfo.msg && jsonInfo.msg.split(';')
      const handleJsonMsg = []
      if (Array.isArray(jsonMsg) && jsonMsg.length > 0) {
        for (const item of jsonMsg) {
          const itemInfo = item.split(':')
          if (itemInfo.length > 1) {
            const first = itemInfo[0].split('/')
            let last = itemInfo[1]
            if ((first.length - 3) >= 0) {
              const lastField = first[first.length - 1]
              if (isNaN(Number.parseInt(lastField))) {
                const tableName1 = first[2] || ''
                const tableName2 = first[first.length - 3] || ''
                const tableNames = []
                if (tableName1 !== 'data')tableNames.push(tableName1)
                if (tableName2 !== tableName1 && tableName2 !== 'data') tableNames.push(tableName2)
                itemInfo[0] = await this.converField(tableNames, first)
              } else if (Object.prototype.toString.call(Number.parseInt(lastField)) === '[object Number]') {
                const index1 = last.indexOf('[')
                const index2 = last.indexOf(']')
                if (index1 !== -1 && index2 !== -1) {
                  const field = last.slice(index1 + 1, index2)
                  let fieldVal = ''
                  const tableName = first[first.length - 2]
                  let name = tableName.split('')
                  if (name && name.length > 2) {
                    name.splice(2, 0, '_')
                  }
                  name = name.join('')
                  if (this.tableDataInfo.length === 0 || this.tableDataInfo.findIndex(item => item.name === name.toUpperCase()) === -1) {
                    const res = await interfaceMonitorService.getColumnByTableName(name.toUpperCase())
                    const obj = {}
                    obj.name = name.toUpperCase()
                    obj.value = res
                    this.tableDataInfo.push(obj)
                  }
                  this.tableDataInfo.forEach(item => {
                    if (item.name === name.toUpperCase()) {
                      const value = item.value
                      value.forEach(val => {
                        if (val.COLUMN_NAME === field) {
                          fieldVal = val.COMMENTS
                        }
                      })
                    }
                  })
                  last = last.replace(field, `${fieldVal}/${field}`)
                }
                itemInfo[1] = last
              }
            }
          }
          handleJsonMsg.push(itemInfo.join(''))
        }
      }
      return handleJsonMsg.join(';')
    },
    //转换字段
    async converField (tableNames, first) {
      const names = []
      for (const item of tableNames) {
        let name = item.split('')
        if (name && name.length > 2) {
          name.splice(2, 0, '_')
        }
        name = name.join('')
        names.push(name.toUpperCase())
        if (this.tableDataInfo.length === 0 || this.tableDataInfo.findIndex(item => item.name === name.toUpperCase()) === -1) {
          const res = await projectReportService.getColumnByTableName(name.toUpperCase())
          const obj = {}
          obj.name = name.toUpperCase()
          obj.value = []
          if (res && Array.isArray(res)) obj.value = res
          this.tableDataInfo.push(obj)
        }
      }
      const handleJson = this.convertInfo(names, first)
      return handleJson.join('/')
    },
    //更换页面
    onPageChange(page, pageSize) {
      if (page !== this.currentPage) {
        this.currentPage = page
        this.$emit('pageSizeChange',page)
        this.selectedDetails = []
      }
    },
    //判断重推批复按钮是否显示：当前点击接口是否为’批复‘环节的批复文件
    showMaterialRepushButton(){
      const activityName = this.selectedDetails.find(item => item.id === this.activeKey).activityName
      return this.selectedStage.stageName === '批复' && activityName === '批复文件';
    },
    //判断重推批复按钮是否可点击：只有最后一次接口调用成功并且和3.0有联系的项目才能点击
    disableMaterialRepushButton(){
      sqlService.listQuery({
        params: {},
        data: {
          sqlConfigName: 'hasExtRelationProject',
          params: {
            projectId: this.projectId
          }
        }
      }).then(res => {
        if (res && res[0].count > 0 && this.selectedStage.details[this.selectedStage.details.length - 1].state === '调用成功') {
          this.disableRepushButton = false
        }
      })
    },
    //重推批复材料
    materialRepush(){
      this.$confirm({
        title: '补推办结材料到3.0',
        content: '确认执行补推办结材料到3.0的操作，执行后会删除3.0现有办结材料并重新推送！',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          interfaceMonitorService
            .sendEndInvProjectMaterial({ projectId: this.projectId, type: true }, null)
            .then((res) => {
              if (res) {
                this.$message.success('补推成功')
                setTimeout(function () {
                  window.close()
                }, 1500)
              } else {
                this.$message.error('补推失败')
              }
            })
        }
      })
    },
    //接口重推
    interfaceRepush() {

    }
  }
}
</script>

<style scoped lang="less">
.log-details {
  padding: 10px;
  background-color: white;

  .stage-box {
    height: 40%;
    background-color: rgba(214, 217, 220, 0.4);
  }

  .content-button-list {
    justify-content: flex-end;
    align-items: flex-end;
    padding: 10px;
  }
  .content-button {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 30px;
    width: 90px;
    background-color: #169bd5;
    cursor: pointer;
    border-radius:5%;
    color: white;
    font-weight: bold;
    margin-left: 10px;
  }

  button[disabled] {
    color: white !important;
    background-color: #aaaaaa !important;
  }

  .projectMaterials {
    width: 100%;
    height: 100%;
  }

  /deep/ .content-tab {
    .ant-tabs-top-content {
      //overflow: hidden;
      height: calc(100% - 36px);
    }

    .ant-descriptions-row {
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }

    .ant-descriptions-item-content {
      padding: 10px;
      flex: 1;
      overflow: hidden;
    }

    .ant-descriptions-item-label {
      padding: 10px;
      min-width: 150px;
    }

    .ant-tabs-tabpane-active {
      overflow-y: auto;
    }

    .ant-descriptions-item-content {
      max-width: 300px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
    }

  }

  /deep/ .jsoneditor-vue {
    height: 100%;
  }

  /deep/ .jsoneditor-poweredBy {
    display: none;
  }

}
</style>
